// For sanity
#![feature(nll)]

// Easier to create safe synchronization primitives
#![feature(optin_builtin_traits)]

// For converting Rust results into FFI results
#![feature(try_trait)]

// For using the `RangeBounds` trait
#![feature(range_contains)]

// Result <-> Option
#![feature(transpose_result)]

// For using the `SliceIndex` trait
#![feature(slice_index_methods)]

// For micro benchmarking internals
#![cfg_attr(test, feature(test))]

#[macro_use]
extern crate diesel;
extern crate dotenv;
extern crate chrono;

pub mod models;
pub mod schema;

use diesel::prelude::*;
use chrono::prelude::*;
use dotenv::dotenv;
use std::env;


use self::models::{Post, NewPost, EditPost };

pub fn create_post<'a>(conn: &MysqlConnection, cat_id: &'a str, author_id: &'a str, title: &'a str, body: &'a str) -> Post {
    use schema::posts;

    let utc: DateTime<Utc> = Utc::now();

    let new_post = NewPost {
        cat_id: cat_id,
        author_id: author_id,
        title: title,
        body: body,
        create_at: utc,
        update_at: utc
    };

    diesel::insert_into(posts::table)
        .values(&new_post)
        .get_result(conn)
        .expect("Error saving new post")
}

pub fn modify_post<'a>(conn: &MysqlConnection, id: &'a str, cat_id: &'a str, title: &'a str, body: &'a str) -> Post {
    use schema::posts;

    let utc: DateTime<Utc> = Utc::now();

    let edit_post = EditPost {
        cat_id: cat_id,
        title: title,
        body: body,
        update_at: utc
    };

    let updated_row = diesel::update(posts.filter(id.eq(id)))
        // .set(name.eq("James")) 
        .get_result(&connection)
        .expect("Error saving edit post")
}